<?php

namespace StudyBuddy;

/**
 *
 * Class for parsing and displaying user's votes stats
 * total votes as well as up/down count
 */
class UserVotesBlock extends StudyBuddyObject {

    public static function get(Registry $oRegistry, User $oUser) {

        $uid = $oUser->getUid();
        $db = $oRegistry->Mongo->getDb();

        $map = new \MongoCode("function() { emit(this.t, 1); }");
        $reduce = new \MongoCode("function(k, vals) { " .
                        "var sum = 0;" .
                        "for (var i in vals) {" .
                        "sum += vals[i];" .
                        "}" .
                        "return sum; }");

        $votes = $db->command(
                array(
                    "mapreduce" => "VOTES",
                    "map" => $map,
                    "reduce" => $reduce,
                    "query" => array("i_uid" => $uid)
                )
        );

        if (empty($votes) || empty($votes['result'])) {
            return '';
        }

        $counter = $db->selectCollection($votes['result'])->find();

        $total = 0;
        $s = '';


        foreach ($counter as $vote) {
            $vars = array('type' => $vote['_id'], 'count' => $vote['value']);
            $total += $vote['value'];
            $s .= \tplVoteCount::parse($vars, false);
        }

        $ret = \tplUserVotes::parse(array('count' => $total, 'stats' => $s, 'username' => $oUser->getDisplayName()));
        d('ret: ' . $ret);

        return $ret;
    }

}
